<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require 'classes/options.php';

class Spider_mcp {
    
        public $EE;
        public $options;
        
	function __construct(){
		$this->EE =& get_instance();
		
		$this->EE->load->library('javascript');
               // $this->EE->load->library('table');
		$this->EE->load->helper('form');
		$this->EE->load->library('form_validation');
		$this->EE->cp->set_right_nav(array(
						'New campaign'=>BASE.AMP.'C=addons_modules'.AMP.'M=show_module_cp'
						.AMP.'module=spider'.AMP.'method=index',
						'Configure Apis'=>BASE.AMP.'C=addons_modules'.AMP.'M=show_module_cp'
						.AMP.'module=spider'.AMP.'method=apiConfigure',
						'Configure Field Group'=>BASE.AMP.'C=addons_modules'.AMP.'M=show_module_cp'
						.AMP.'module=spider'.AMP.'method=configFieldGroup',
						'Edit Campaigns'=>BASE.AMP.'C=addons_modules'.AMP.'M=show_module_cp'
						.AMP.'module=spider'.AMP.'method=edit'
				
			));
		$this->EE->cp->set_variable('cp_page_title', $this->EE->lang->line('spider_module_name'));
		$this->options=new Options();
		$this->EE->form_validation->set_error_delimiters('<p class="notice">', '</p>');
	}
	
	function index(){
		$this->EE->javascript->output(array('jQuery(".mainTable tr:odd").addClass("odd");'));
                $this->EE->javascript->compile();
                
                $vars['msg']=isset($_GET['msg']) ? lang('create_a_campaign first') : '';
		$this->EE->form_validation->set_rules('campaign_name', 'campaign', 'required');
		$this->EE->form_validation->set_rules('no_of_entry', 'Entries per run', 'required|is_natural_no_zero');
		$this->EE->form_validation->set_rules('keyword', 'Keyword', 'required');
		$this->EE->form_validation->set_rules('api[]', 'Api', 'required');
		
		if($this->EE->form_validation->run()===TRUE){
			$tableName=$_POST['tableName'];
			unset($_POST['tableName']);
			unset($_POST['save']);
			$_POST['api']=serialize($_POST['api']);
			if($this->EE->db->insert($tableName, $_POST)===TRUE){
				$vars['msg']="Campin Created";
			}
		}

		$vars['apiNames']=$this->options->getApinames();
		$vars['channel_name'] = $this->fetchChannels();
		$vars['action_url']='C=addons_modules&M=show_module_cp&module=spider&method=index';
		$vars['hidden']=array('tableName'=>'spider_campaign');
		$vars['campaign']=array('name'=>'campaign_name', 'style'=>'width:65%');
		$vars['noOfEntry']=array('name'=>'no_of_entry', 'style'=>'width:65%');
		$vars['keyword']=array('name'=>'keyword', 'rows'=>'5', 'cols'=>'20','style'=>'width:65%');
		
		return $this->EE->load->view('index', $vars, TRUE);
	}
	
	function apiConfigure(){
		$this->EE->javascript->output(array('jQuery(".templateTable tr:even").addClass("even");'));
                $this->EE->javascript->output(array('jQuery(":checkbox").each(function(){
                                                        className=jQuery(this).attr("name");
                                                        if(jQuery(this).is(":checked")){
                                                            jQuery("."+className).removeAttr("disabled");
                                                        }else{
                                                            jQuery(":hidden[name="+className+"]").val("0");
                                                        }
                                                    });'
                                                    ));
                $this->EE->javascript->output(array('jQuery(":checkbox").click(function(){
										   className=jQuery(this).attr("name");
										   if(jQuery(this).is(":checked")){
												if(jQuery("."+className+"").attr("disabled")){
													jQuery("."+className+"").removeAttr("disabled");
                                                                                                        jQuery(this).prev().val("1");
												}

											}
											else{
												if(!jQuery("."+className+"").attr("disabled")){
													jQuery("."+className+"").attr("disabled", "disabled");
                                                                                                        jQuery(this).prev().val("0");
												}
											}

										});
										')
		);
                $this->EE->javascript->compile();

                $vars['msg']='';
		$vars['sucessMsg']='';
		
		if (isset($_POST['optionSave'])){
			$vars['sucessMsg']=$this->saveApiConfigure();
		}
		$vars['campaigns']=$this->fetchcampaigns();
		if (empty($vars['campaigns'])){
			$redirectUrl=BASE.AMP.'C=addons_modules'.AMP.'M=show_module_cp'.AMP.'module=spider'.AMP.'method=index'.AMP.'msg=msg';
                        $this->EE->session->set_flashdata('message_success', lang('create_a_campaign first'));
			$this->EE->functions->redirect($redirectUrl);
		}
		$vars['apiNames']=$this->options->getApinames();
		$vars['currentcampaignId']=isset($_GET['campaignId']) ? $_GET['campaignId'] : $vars['campaigns'][0]['campaign_id'];
		$vars['selectedApis']=$this->selectedApi($vars['campaigns'], $vars['currentcampaignId']);
		$vars['currentApi']=isset($_GET['api']) ? $_GET['api'] : $vars['selectedApis'][0];
		$vars['optionArray']=($this->optionArray($vars['currentcampaignId'], $vars['currentApi'])===FALSE)?$this->options->options[$vars['currentApi']]:$this->optionArray($vars['currentcampaignId'], $vars['currentApi']);
		
		return $this->EE->load->view('apiConfiqure', $vars, TRUE);
	}
        
        /*
         * @todo validation for unique fields
         */
	function configFieldGroup(){
		$this->EE->javascript->output(array('jQuery(".templateTable tr:even").addClass("even");'));
                $this->EE->javascript->compile();
                
                $vars['msg']='';
		$vars['sucessMsg']='';
		if (isset($_POST['optionSave'])){
			$tableName=$_POST['tableName'];
			$api=$_POST['api'];
			$campaignId=$_POST['campaign_id'];
			unset($_POST['tableName']);
			unset($_POST['api']);
			unset($_POST['optionSave']);
			unset($_POST['campaign_id']);
			
			$vars['sucessMsg']=$this->saveFieldGroup($_POST, $tableName, $api, $campaignId)===TRUE?'Configaration Saved':'<span class="notice">Configaration not saved</span>';
		}
		$vars['campaigns']=$this->fetchcampaigns();
		if (empty($vars['campaigns'])){
			$redirectUrl=BASE.AMP.'C=addons_modules'.AMP.'M=show_module_cp'.AMP.'module=spider'.AMP.'method=index'.AMP.'msg=msg';
			$this->EE->functions->redirect($redirectUrl);
		}
		$vars['options']=$this->options;
		$vars['currentcampaignId']=isset($_GET['campaignId']) ? $_GET['campaignId'] : $vars['campaigns'][0]['campaign_id'];
		$vars['currentChannelId']=($this->currentChannelId($vars['currentcampaignId'])===FALSE) ? 1 : $this->currentChannelId($vars['currentcampaignId']);
                $vars['selectedApis']=$this->selectedApi($vars['campaigns'], $vars['currentcampaignId']);
                $vars['currentApi']=isset($_GET['api']) ? $_GET['api'] : current($vars['selectedApis']);
		$vars['fieldGroup']=$this->fetchFields($vars['currentChannelId']);
		$vars['fieldOptions']=$this->fetchOptions($vars['currentApi'], $vars['currentcampaignId']);
                //pr($vars['fieldOptions']);    
		return $this->EE->load->view('configFieldGroup', $vars, TRUE);
	}
        
	function edit(){
		$this->EE->javascript->output(array('jQuery(".mainTable tr:odd").addClass("odd");
                                                     jQuery(".mainTable").tablesorter({
                                                         headers: {0: {sorter: false}, 2:{sorter:false}},
                                                         widgets: ["zebra"]
                                                         });
                                                    '));
                $this->EE->javascript->output(array('jQuery(".toggle_all").click(function(){
                                                        if(jQuery(this).is(":checked")){
                                                            jQuery(".toggle").attr("checked", true);
                                                        }else{
                                                            jQuery(".toggle").attr("checked", false);
                                                        }
                                                    });
                                                    '));
                $this->EE->javascript->compile();
                
                $msg='';
                if(isset ($_POST['toggle'])){
                    
                    foreach($_POST['toggle'] as $toggle){
                        $this->EE->db->delete($_POST['tableName'], array('campaign_id'=>$toggle));
                    }
                }
		if (isset($_GET['campaignId']) && $_GET['action']=='delete'){
			if ($this->EE->db->delete('spider_campaign', array('campaign_id' => $_GET['campaignId']))){
				$msg=$_GET['campaignName'];
				$msg .= ' Deleted Successfully';
			}
		}
                if (isset($_GET['campaignId']) && $_GET['action']=='activation'){
                    $this->EE->db->where('campaign_id', $_GET['campaignId']);
                    if($this->EE->db->update('spider_campaign', array('active'=>$_GET['param']))){
                            $msg=$_GET['campaignName'];
                            $msg.=' Updated Successfully';
                    }
                }
                $vars['msg']=isset($_GET['msg'])?$_GET['msg']:$msg;
		$vars['campaigns']=$this->fetchcampaigns();
		if (empty($vars['campaigns'])){
			$redirectUrl=BASE.AMP.'C=addons_modules'.AMP.'M=show_module_cp'.AMP.'module=spider'.AMP.'method=index'.AMP.'msg=msg';
			$this->EE->functions->redirect($redirectUrl);
		}
                
		return $this->EE->load->view('edit', $vars, TRUE);
	}
        
	function editcampaign(){
		$this->EE->javascript->output(array('jQuery(".mainTable tr:odd").addClass("odd");'));
                $this->EE->javascript->compile();
                
                $vars['msg']='';
		$this->EE->form_validation->set_rules('campaign_name', 'campaign', 'required');
		$this->EE->form_validation->set_rules('no_of_entry', 'Entries per run', 'required|is_natural_no_zero');
		$this->EE->form_validation->set_rules('keyword', 'Keyword', 'required');
                $this->EE->form_validation->set_rules('api[]', 'Api', 'required');
		
		if($this->EE->form_validation->run()===TRUE){
			$tableName=$_POST['tableName'];
			$id=$_POST['campaign_id'];
			unset($_POST['campaign_id']);
			unset($_POST['tableName']);
			unset($_POST['save']);
                        $_POST['api']=serialize($_POST['api']);
			$this->EE->db->where('campaign_id', $id);
			if ($this->EE->db->update($tableName, $_POST)){
				$vars['msg']='Updated';
			} 
			
		}
		$vars['apiNames']=$this->options->getApinames();
		$vars['campaigns']=$this->fetchcampaigns();
		if (empty($vars['campaigns'])){
			$redirectUrl=BASE.AMP.'C=addons_modules'.AMP.'M=show_module_cp'.AMP.'module=spider'.AMP.'method=index'.AMP.'msg=msg';
			$this->EE->functions->redirect($redirectUrl);
		}
		$vars['currentcampaignId']=isset($_GET['campaignId']) ? $_GET['campaignId'] : $vars['campaigns'][0]['campaign_id'];
		$query=$this->EE->db->get_where('spider_campaign', array('campaign_id'=>$vars['currentcampaignId']));
		$vars['data']=$query->result_array();
		$vars['channel_name'] = $this->fetchChannels();
		$vars['campaign']=array('name'=>'campaign_name', 'style'=>'width:65%', 'value'=>$vars['data'][0]['campaign_name']);
		$vars['noOfEntry']=array('name'=>'no_of_entry', 'style'=>'width:65%', 'value'=>$vars['data'][0]['no_of_entry']);
		$vars['keyword']=array('name'=>'keyword', 'rows'=>'5', 'cols'=>'20','style'=>'width:65%', 'value'=>$vars['data'][0]['keyword']);
		return $this->EE->load->view('editCampaign', $vars, TRUE);
	}
        
	function fetchChannels(){
		$query=$this->EE->db->get('channels');
		return $query->result_array();	
	}
	
	function fetchcampaigns(){
                $campaigns=$this->EE->db->get('spider_campaign');
		return $campaigns->result_array();
	}
	
	function checkcampaign($id, $tableName){
                $this->EE->db->where(array('campaign_id'=>$id));
                if($this->EE->db->count_all_results($tableName)==0){
                    return true;
                }
		return FALSE;
	}
        
	function fetchFields($channelId){
		$sql="SELECT ".$this->EE->db->dbprefix('channel_fields').".field_id,".$this->EE->db->dbprefix('channel_fields').".field_name, ".$this->EE->db->dbprefix('channel_fields').".field_fmt  
				FROM ".$this->EE->db->dbprefix('channel_fields')." 
				LEFT JOIN ".$this->EE->db->dbprefix('channels')." 
				ON ".$this->EE->db->dbprefix('channel_fields').".group_id=".$this->EE->db->dbprefix('channels').".field_group
				WHERE ".$this->EE->db->dbprefix('channels').".`field_group`=(
				SELECT field_group
				FROM ".$this->EE->db->dbprefix('channels')."
				WHERE `channel_id` = '$channelId')";
		$query=$this->EE->db->query($sql);
		if ($query->num_rows() > 0){
			return $query->result_array();
		}
		return FALSE;
	}
        
	function currentChannelId($id){
		$query=$this->EE->db->get_where('spider_campaign', array('campaign_id'=>$id));
		if ($query->num_rows()==1){
			$arr=$query->result_array();
			return $arr[0]['channel_id'];	
		}
		
		return FALSE;
	}
        
	function optionArray($campaignId, $api){
		//$sql="SELECT * FROM `exp_spider_";
		//$sql.="$api` WHERE `campaign_id`='$campaignId'";
                $query=$this->EE->db->get_where('spider_'.$api, array('campaign_id'=>$campaignId));
		//$query=$this->EE->db->query($sql);
		if ($query->num_rows()==0){
			return FALSE;
		}
		$result=$query->result_array();
		unset($result[0]['campaign_id']);
		unset($result[0]['id']);
		$arr=$this->options->options[$api];
		foreach ($result[0] as $key=>$value){
			$text='value';
			$arrValue=$value;
			if($arr[$key]['type']=='form_checkbox'){
				$arrValue=($value=='1')?TRUE:FALSE;
				$text='checked';
				unset($arr[$key]['attribute']['checked']);
			}
			$att=$arr[$key]['attribute']+array($text=>$arrValue);
			$arr[$key]['attribute']=$att;
		}
		return $arr;
	}
        
	function fetchOptions($api, $campaignId){
		$arr=$this->options->fields[$api];
		$arr=$this->checkFields($api, $campaignId, $arr);
		
                $query=$this->EE->db->get_where('spider_fields', array('campaign_id'=>$campaignId, 'api_name'=>$api));
		if ($query->num_rows()!=0) {
			$result=$query->result_array();
			$results=unserialize($result[0]['fields']);
			foreach ($results as $key=>$value){
				if (isset($arr['common'])){
					
					if (array_key_exists($key, $arr['common'])){
						unset($arr['common'][$key]['attribute']);
						$arr['common'][$key]['attribute']=array('checked'=>'checked');
						$arr['common'][$key]['fieldId']=$value;
					}
				}
				if (isset($arr['extra'])){
					if (array_key_exists($key, $arr['extra'])){
						unset($arr['extra'][$key]['attribute']);
						$arr['extra'][$key]['attribute']=array('checked'=>'checked');
						$arr['extra'][$key]['fieldId']=$value;
					}
				}
			}
		}
		return $arr;
	}
        
	function checkFields($api, $campaignId, $arr){
		$extraFields=$this->options->optionalFields[$api];
                
                $query=$this->EE->db->get_where('spider_'.$api, array('campaign_id'=>$campaignId));
                if($query->num_rows==0){
                    unset ($arr['extra']);
                    return $arr;
                }
                $results=$query->row_array();
                //print_r($extraFields);
		foreach ($extraFields as $key=>$value){
                    if($results[$key]==0){
                        foreach ($value as $v){
                            unset ($arr['extra'][$v]);
                        }
                    }
		}
                if(empty ($arr['extra'])){
                    unset ($arr['extra']);
                }
                return $arr;
	}
	
	function saveApiConfigure(){
            
                foreach ($_POST as $key=>$value){
                    if($value==""){
                        unset ($_POST[$key]);
                    }
                }
		unset($_POST['optionSave']);

                $this->EE->form_validation->set_rules($this->options->validation[$_POST['apiName']]);
                if($this->EE->form_validation->run()===TRUE){
                        unset($_POST['apiName']);
                        $tableName=$_POST['tableName'];
                        $id=$_POST['campaign_id'];
                        unset($_POST['tableName']);
                        if($this->checkcampaign($_POST['campaign_id'], $tableName)===FALSE){
                                $id=$_POST['campaign_id'];
                                return $this->EE->db->update($tableName, $_POST, array('campaign_id' => $id))===TRUE ? 'Configaraion Updated' : '<span class="notice">Configaraion not Saved</span>';
                        }
                        else{
                                return $this->EE->db->insert($tableName, $_POST)===TRUE ? 'Configaraion Saved' : '<span class="notice">Configaraion not Saved</span>';
                        }
                }
	}
	
	function saveFieldGroup($_POST, $tableName, $api, $campaignId, $arr=array()){
                $currentChannelId=($this->currentChannelId($campaignId)===FALSE) ? 1 : $this->currentChannelId($campaignId);
                $allFields=$this->fetchFields($currentChannelId);
                foreach ($allFields as $allField){
                        $fieldFormating[$allField['field_id']]=$allField['field_fmt'];
                }
                
		foreach ($_POST as $key=>$value){
			if (substr($key, 0, strpos($key, '_'))!='fieldGroup'){
				$arr[$key]=$_POST['fieldGroup_'.$key];
                                $arr['fmt_'.$key]=$fieldFormating[$_POST['fieldGroup_'.$key]];
			}
		}
                
		$str=serialize($arr);
                
		$data=array('campaign_id'=>$campaignId, 'api_name'=>$api, 'fields'=>$str);
		$this->EE->db->where(array('campaign_id'=> $campaignId, 'api_name'=>$api));
		if ($this->EE->db->count_all_results($tableName)==0){
			if ($this->EE->db->insert($tableName, $data)){
				return TRUE;
			}
			return FALSE;
		}
		else{
			if($this->EE->db->update($tableName, $data)){
                            return TRUE;
                        }
                        return FALSE;
		}
		
	}
        
	function selectedApi($camapins, $currentcampaignId){
		foreach ($camapins as $camapin){
			if ($camapin['campaign_id']==$currentcampaignId){
				return unserialize($camapin['api']);
			}
		}
	}
}


function pr($var){
    echo '<pre>';
    print_r($var);
    echo '</pre>';
}